package com.cn.ssm.controller;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import com.cn.ssm.model.User;
import com.cn.ssm.service.IUserService;

import java.util.List;

@Controller
@RequestMapping("/user")
public class UserController {
    @Resource
    private IUserService userService;

    //	@RequestMapping("/userInfo")
//	public String userInfo(HttpServletRequest request,Model model){
//		int userId = Integer.parseInt(request.getParameter("id"));
//		User user = this.userService.getUserById(userId);
//		model.addAttribute("user", user);
//		return "userInfo";
//	}
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public String userAdd(Model model, @ModelAttribute("form") User user) {
//		int userId = Integer.parseInt(request.getParameter("id"));

       /* User user = new User();
        user.setUserName(userName);
        user.setAge(Integer.parseInt(age));
        user.setPassword(password);*/
        int cun = this.userService.addUserSelective(user);
        model.addAttribute("user", user);
        if(cun>0){
            return "redirect:/user/users";
        }
        return "user/add";
    }

    @RequestMapping(value = "/add", method = RequestMethod.GET)
    public String userAdd() {

        return "user/add";
    }

    @RequestMapping("/user/detail")
    public String userInfo(@RequestParam int id, Model model) {
//		int userId = Integer.parseInt(request.getParameter("id"));
        User user = this.userService.getUserById(id);
        model.addAttribute("user", user);
        return "user/detail";
    }

    @RequestMapping(path = "/detail/{id}")
    public String userDetail(@PathVariable int id, Model model) {
        User user = this.userService.getUserById(id);
        model.addAttribute("user", user);
        return "user/detail";
    }

    @ResponseBody
    @RequestMapping(path = "/userInfoJson/{id}")
    public User userInfoJson(@PathVariable int id) {
        User user = this.userService.getUserById(id);
        return user;
    }

    @RequestMapping(path = "/deleteUser/{id}")
    public String deleteUser(@PathVariable int id) {
        int count = this.userService.deleteUserById(id);
        if(count>0){
            return "redirect:/user/users";
        }
        return "user/users";
    }

    @RequestMapping(path = "/users")
    public String UserList(Model model) {
        List<User> users = this.userService.getAllUser();
        model.addAttribute("users", users);
        model.addAttribute("a", "41544");
        return "user/users";
    }
}